<?php

class MyString
{
  static function html_entity_decode($string)
  {
    $string=str_replace("’","'",$string);
    $string=str_replace("â€™","'",$string);
    $string=str_replace("&rsquo;","'",$string);
    $string=str_replace("&#039;","'",$string);
    $string=html_entity_decode($string);
    return $string;
  }
  static function tomultiline($string,$len,$spacer=" ")
  {
    $string=str_replace("\n",$spacer,$string);
    $string=str_replace("\t",$spacer,$string);
    $words=explode($spacer,$string);
    
    $lines=array();
    $line="";
    foreach($words as $word)
    {
      //if word does not fit this line
      if(strlen($word)>$len)
      {
        //if buffer is not empty,
        if($line!="")
        {
          //flush it
          $lines[]=$line;
          $line="";
        }
        //chop it up into $len-1 size pieces and give each piece its own line
        $array=array();
        $index=0;
        $remaining=strlen($word);
        do
        {
          $lines[]=substr($word,$index,$len-1)."-";
          $index+=$len-1;
          $remaining-=$len-1;
        }
        while($remaining>$len);
        //add the last (short) substring
        $lines[]=substr($word,$index);
      }
      elseif(strlen($word)+strlen($line)>$len)
      {
        //flush buffer
        $lines[]=$line;
        $line=$word;
      }
      //enough space in buffer - add word to buffer
      else
      {
        //if buffer empty, just add line
        if($line=="")
          $line=$word;
        //else add spacer and line
        else
          $line.=$spacer.$word;
      }
    }
    //add last line to buffer
    if($line!="")
      $lines[]=$line;

    return $lines;
  }
  static function tomultilinehtml($string,$len)
  {
    $string=MyString::html_entity_decode($string);
    $array=MyString::tomultiline($string,$len);
    $string=implode("<br>",$array);
    return $string;
  }
  //as used in journal pdfs, etc
  static function processmultiline(&$content,$arraylength,$string,$col,$width,$spacer,$skiplines=0)
  {
    $string=MyString::html_entity_decode($string);
    $array=MyString::tomultiline($string,$width,$spacer);
    $emptyarray=array();
    //generate an empty array of length $arraylength
    foreach(range(1,$arraylength) as $count)
    {
      $emptyarray[]="";
    }
    foreach($array as $index=>$line)
    {
      if(!isset($content[$index+$skiplines]))$content[$index+$skiplines]=$emptyarray;
      $content[$index+$skiplines][$col]=$line;
    }
    return count($array);
  }
}
